package com.newpage.module_gather.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import androidx.recyclerview.widget.RecyclerView;

import com.newpage.module_gather.R;

import java.util.ArrayList;
import java.util.List;


/**
 * 首页选择弹框适配器
 */
public class CommonPopAdapter extends RecyclerView.Adapter{

    private List<String> mData = new ArrayList<>();
    private Context mContext;
    private int selectIndex = 0;
    public CommonPopAdapter(Context context) {
        this.mContext = context;
    }

    public void setData(List<String> data){
        if (data!=null){
            mData.clear();
            mData.addAll(data);
            notifyDataSetChanged();
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(viewType == 1) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.gather_common_item_pop, parent, false);
            return new CommonViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof CommonViewHolder) {
            ((CommonViewHolder)holder).bindData(position);
        }
    }

    @Override
    public int getItemCount() {
        if(mData == null) {
            return 0;
        }
        return mData.size();
    }

    public int getSelectIndex() {
        return selectIndex;
    }

    public void setSelectIndex(int selectIndex) {
        this.selectIndex = selectIndex;
    }

    @Override
    public int getItemViewType(int position) {
        return 1;
    }

    class CommonViewHolder<T> extends RecyclerView.ViewHolder{
        TextView tv_pop;

        public CommonViewHolder( View itemView) {
            super(itemView);
           tv_pop = itemView.findViewById(R.id.tv_common_pop);
        }
        public void bindData(final int position) {
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onClick(position);
                        setSelectIndex(position);
                        notifyDataSetChanged();
                    }
                }
            });

            tv_pop.setText("" + mData.get(position));
            if (getSelectIndex() == position){
                tv_pop.setSelected(true);
            }else {
                tv_pop.setSelected(false);
            }
        }
    }



    //第一步 定义接口
    public interface OnItemClickListener {
        void onClick(int position);
    }
    private OnItemClickListener listener;
    //第二步， 写一个公共的方法
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

}
